//
//  WKScanerDetailVC.m
//  V-Learn
//
//  Created by Apple on 2019/6/27.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "WKScanerDetailVC.h"
#import "ZFTableHeaderView.h"
#import "ZFPlayerControlView.h"
#import <ZFPlayer/ZFPlayer.h>
#import "ZFAVPlayerManager.h"
#import "VKRecordInfoModel.h"
#import "WKHotclockInfoVOListModel.h"
#import "ZSDTCoreTextCell.h"
#import "ZSDTCoreTextTools.h"
#import "WKScanerCell.h"
@interface WKScanerDetailVC ()<UITableViewDelegate,UITableViewDataSource,DTAttributedTextContentViewDelegate,DTLazyImageViewDelegate>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) ZFTableHeaderView *headerViewTwo;

@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) ZFPlayerControlView *controlView;
//@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UILabel *contentLab;
@property (nonatomic, strong) UIButton *followBtn;
@property (nonatomic, strong) UIButton *zanButton;
@property (nonatomic, strong) NSString *isAtten;/**关注*/
@property (nonatomic, strong) NSString *isPrase;/**赞*/

@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIImageView *footImageView;

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIImageView *headerImageView;

//普通单元格与富文本单元格
@property (nonatomic, copy) NSString *cellID_Normal;
@property (nonatomic, copy) NSString *cellID_DTCoreText;

//类似tabelView的缓冲池，用于存放图片大小
@property (nonatomic, strong) NSCache *imageSizeCache;
@property (nonatomic,strong)NSCache *cellCache;
//表视图数据源
@property (nonatomic, strong) NSArray  *dataSource;
@property (nonatomic,assign)BOOL isScrolling;
@property (nonatomic, copy) NSString *htmlString;

@end

@implementation WKScanerDetailVC
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LBNAVBAR_HEIGHT, ScreenW, ScreenH-LBNAVBAR_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    }
    return _tableView;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化控件
    [self setupUI];

    _imageSizeCache = [[NSCache alloc] init];
    _cellCache = [[NSCache alloc] init];
    _cellCache.totalCostLimit = 10;
    _cellCache.countLimit = 10;
    [self requestData];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.player.currentPlayerManager.assetURL = nil;
    self.player = nil;
}
#pragma mark - 获取后台数据
- (void)requestData{
    
    [WYHXNetWorkManager get:WKQueryFreeCourseInfo_WKURL params:@{@"courseId":self.courseId} completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
//            VKRecordInfoModel *model = self.model.clockInfoVOList[0];

            NSString *url = responseObj[@"data"][@"url"];
            NSString *html = responseObj[@"data"][@"info"];
            self.htmlString = html;
            NSString *urlString = [NSString stringWithFormat:@"%@%@",Public_URL,url];
            //处理带中文的url
            NSString *encodeUrlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            //设置从那开始播放

            
            if ([self.courseType integerValue]==1) {
                self.controlView.portraitControlView.bgImageView.hidden = NO;
                self.controlView.landScapeControlView.bgImageView.hidden = NO;
            }else{
                self.controlView.portraitControlView.bgImageView.hidden = YES;
                self.controlView.landScapeControlView.bgImageView.hidden = YES;
            }
            [self.controlView showTitle:@"" coverURLString:self.thunbnaiUrl fullScreenMode:ZFFullScreenModeLandscape];
            [self.controlView.portraitControlView.bgImageView sd_setImageWithURL:[NSURL URLWithString:self.thunbnaiUrl] placeholderImage:[UIImage imageNamed:@"wk_list_bgimg"]];
            [self.headerViewTwo.coverImageView sd_setImageWithURL:[NSURL URLWithString:self.thunbnaiUrl] placeholderImage:[UIImage imageNamed:@"wk_list_bgimg"]];
            self.player.currentPlayerManager.assetURL = [NSURL URLWithString:encodeUrlString];
        }
        [self.tableView reloadData];
    }];
}
- (void)setupUI{
    self.navigationItem.title = @"课程详情";
    self.headerView = [UIView new];
    self.headerView.frame = CGRectMake(0, 0, ScreenW, 277*kScaleFit);
    

    //创建视频
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    self.player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:self.headerViewTwo.coverImageView];
    self.player.controlView = self.controlView;
    
    self.headerViewTwo.layer.cornerRadius = 5;
    self.headerViewTwo.layer.masksToBounds = YES;
    [self.controlView.landScapeControlView.kuaijinBtn addTarget:self action:@selector(clickKuaiPlayBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlView.portraitControlView.kuaiButton addTarget:self action:@selector(clickKuaiPlayBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlView.portraitControlView.playOrPauseBtn addTarget:self action:@selector(clickPalyOrPauseBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlView.landScapeControlView.playOrPauseBtn addTarget:self action:@selector(clickPalyOrPauseBtn:) forControlEvents:UIControlEventTouchUpInside];
    @weakify(self)
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        @strongify(self)
        [self setNeedsStatusBarAppearanceUpdate];
        self.tableView.scrollsToTop = !isFullScreen;
        [self.controlView.portraitControlView.bgImageView sd_setImageWithURL:[NSURL URLWithString:self.thunbnaiUrl] placeholderImage:[UIImage imageNamed:@"wk_list_bgimg"]];
        [self.controlView.landScapeControlView.bgImageView sd_setImageWithURL:[NSURL URLWithString:self.thunbnaiUrl] placeholderImage:[UIImage imageNamed:@"wk_list_bgimg"]];
        if ([self.courseType integerValue]==1) {
            self.controlView.portraitControlView.bgImageView.hidden = NO;
            self.controlView.landScapeControlView.bgImageView.hidden = NO;
        }else{
            self.controlView.portraitControlView.bgImageView.hidden = YES;
            self.controlView.landScapeControlView.bgImageView.hidden = YES;
        }
    };
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        @strongify(self)
        
        [self.controlView resetControlView];
        [self.player.currentPlayerManager seekToTime:0 completionHandler:nil];
        self.player.currentPlayerManager.rate = 1.0;
        
    };
    self.player.WWANAutoPlay = NO;
    [self.headerView addSubview:self.headerViewTwo];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 50;
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = [UIView new];
    [self.view addSubview:self.tableView];
    [self.headerViewTwo makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(5);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.bottom.mas_equalTo(0);
    }];
    
//    self.controlView.portraitControlView.bgImageView.hidden = YES;
//    self.controlView.landScapeControlView.bgImageView.hidden = YES;
    [self.controlView showTitle:@"" coverURLString:nil fullScreenMode:ZFFullScreenModeLandscape];

//    self.player.currentPlayerManager.assetURL = [NSURL URLWithString:@"https://www.vlearnjy.com//clockVideo/156/2019-06-18/15608468382F3ED2E1-3DD5-4264-9678-21F477C73C35.mp4"];
    self.controlView.backgroundColor = [UIColor clearColor];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
            self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
}

#pragma mark - 竖屏播放或暂停按钮
- (void)clickPalyOrPauseBtn:(UIButton *)sender{
    
    self.player.currentPlayerManager.rate = 1.0;
}
#pragma mark - 播放快进按钮
- (void)clickKuaiPlayBtn:(UIButton *)sender{
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        self.player.currentPlayerManager.rate = 2.0;
    }else{//第二次是恢复正常
        self.player.currentPlayerManager.rate = 1.0;
    }
}


- (void)jumpLloginviewController{
    LBLoginVC *loginVC = [[LBLoginVC alloc] init];
    loginVC.jumpType = @"1";
    [self.navigationController pushViewController:loginVC animated:YES];

}
- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];
        _controlView.fastViewAnimated = YES;
    }
    return _controlView;
}

- (ZFTableHeaderView *)headerViewTwo {
    if (!_headerViewTwo) {
        _headerViewTwo = [[ZFTableHeaderView alloc] init];
        @weakify(self)
        _headerViewTwo.playCallback = ^{
            @strongify(self)
            
        };
    }
    return _headerViewTwo;
}
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];

    CGFloat y = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    CGFloat h = CGRectGetMaxY(self.view.frame);
    
    self.tableView.frame = CGRectMake(0, LBNAVBAR_HEIGHT, ScreenW, h-LBNAVBAR_HEIGHT);

}

//- (BOOL)shouldAutorotate {
//    return self.player.shouldAutorotate;
//}
//
//- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
//    if (self.player.isFullScreen && self.player.orientationObserver.fullScreenMode == ZFFullScreenModeLandscape) {
//        return UIInterfaceOrientationMaskLandscape;
//    }
//    return UIInterfaceOrientationMaskPortrait;
//}
//
//- (UIStatusBarStyle)preferredStatusBarStyle {
//    if (self.player.isFullScreen) {
//        return UIStatusBarStyleLightContent;
//    }
//    return UIStatusBarStyleDefault;
//}
//
//- (BOOL)prefersStatusBarHidden {
//    return self.player.isStatusBarHidden;
//}
//
//- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
//    return UIStatusBarAnimationSlide;
//}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row==0) {
        WKScanerCell *scannerCell = [WKScanerCell cellWithTableView:tableView];
        scannerCell.selectionStyle = UITableViewCellSelectionStyleNone;
        scannerCell.titleLab.text = self.titleString;
        scannerCell.detailLab.text = self.detailString;
        return scannerCell;
    }else{
        ZSDTCoreTextCell *dtCell = (ZSDTCoreTextCell *) [self tableView:tableView prepareCellForIndexPath:indexPath];
        dtCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return dtCell;
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==1) {
        ZSDTCoreTextCell *cell = (ZSDTCoreTextCell *)[self tableView:tableView prepareCellForIndexPath:indexPath];
        return [cell requiredRowHeightInTableView:tableView];
    }else{
        return UITableViewAutomaticDimension;
    }
    
}
#pragma mark - private Methods
//创建富文本单元格，并更新单元格上的数据
- (ZSDTCoreTextCell *)tableView:(UITableView *)tableView prepareCellForIndexPath:(NSIndexPath *)indexPath{
    NSString *key = [NSString stringWithFormat:@"dtCoreTextCellKEY%ld", (long)indexPath.row];
    ZSDTCoreTextCell *cell = [_cellCache objectForKey:key];
    
    if (!cell){
        cell = [[ZSDTCoreTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:_cellID_DTCoreText];
        //        }
        cell.attributedTextContextView.edgeInsets = UIEdgeInsetsMake(0, 15, 0, 15);
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.hasFixedRowHeight = NO;
        cell.textDelegate = self;
        cell.attributedTextContextView.shouldDrawImages = YES;
        //记录在缓存中
        [_cellCache setObject:cell forKey:key];
    }
    //2.设置数据
    //2.1为富文本单元格设置Html数据
    [cell setHTMLString:self.htmlString];
    //2.2为每个占位图(图片)设置大小，并更新
    for (DTTextAttachment *oneAttachment in cell.attributedTextContextView.layoutFrame.textAttachments) {
        NSValue *sizeValue = [_imageSizeCache objectForKey:oneAttachment.contentURL];
        if (sizeValue) {
            cell.attributedTextContextView.layouter=nil;
            oneAttachment.displaySize = [sizeValue CGSizeValue];
            [cell.attributedTextContextView relayoutText];
        }
    }
    [cell.attributedTextContextView relayoutText];
    return cell;
}

#pragma mark - DTAttributedTextContentViewDelegate
//对于没有在Html标签里设置宽高的图片，在这里为其设置占位
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame{
    if([attachment isKindOfClass:[DTImageTextAttachment class]]){
        ZSDTLazyImageView *imageView = [[ZSDTLazyImageView alloc] initWithFrame:frame];
        imageView.delegate = self;
        imageView.image = [(DTImageTextAttachment *)attachment image];
        imageView.textContentView = attributedTextContentView;
        imageView.url = attachment.contentURL;
        return imageView;
    }
    return nil;
}
//对于无宽高懒加载得到的图片，缓存记录其大小,然后执行表视图更新
- (void)lazyImageView:(ZSDTLazyImageView *)lazyImageView didChangeImageSize:(CGSize)size{
    BOOL needUpdate = NO;
    NSURL *url = lazyImageView.url;
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"contentURL == %@", url];
    /* update all attachments that matchin this URL (possibly multiple
     images with same size)
     */
    for (DTTextAttachment *oneAttachment in [lazyImageView.textContentView.layoutFrame textAttachmentsWithPredicate:pred]){
        // update attachments that have no original size, that also sets the display size
        if (CGSizeEqualToSize(oneAttachment.originalSize, CGSizeZero)){
            oneAttachment.originalSize = size;
            NSValue *sizeValue = [_imageSizeCache objectForKey:oneAttachment.contentURL];
            if (!sizeValue) {
                //将图片大小记录在缓存中，但是这种图片的原始尺寸可能很大，所以这里设置图片的最大宽
                //并且计算高
                CGFloat aspectRatio = size.height / size.width;
                CGFloat width = ZSToolScreenWidth - 15*2;
                CGFloat height = width * aspectRatio;
                CGSize newSize = CGSizeMake(width, height);
                [_imageSizeCache setObject:[NSValue valueWithCGSize:newSize]forKey:url];
            }
            needUpdate = YES;
        }
    }
    
    if (needUpdate){
        //有新的图片尺寸被缓存记录的时候，需要刷新表视图
        //[self reloadCurrentCell];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reloadCurrentCell) object:nil];
        self.isScrolling = NO;
        [self performSelector:@selector(reloadCurrentCell) withObject:nil afterDelay:0.2];
    }
}
- (void)reloadCurrentCell{
    //如果当前表视图在滑动就不执行刷新，因为滑动时候会自动调用表视图的刷新方法
    if (self.isScrolling) {
        return;
    }
    //如果当前表视图没有在滑动，就手动刷新当前在屏幕显示的单元格
    NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
    if(indexPaths){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
        });
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    _isScrolling = YES;
}
- (NSArray *)dataSource{
    if(_dataSource == nil){
        
    }
    return _dataSource;
}



@end
